package com.freight.user.util;

import com.freight.core.common.constant.CommonConstant;
import com.freight.core.common.exception.FreightException;
import com.freight.core.entity.User;
import com.freight.user.dto.UserDto;

import java.util.HashMap;
import java.util.List;

public class UserDtoUtils<T extends UserDto> {

    public static <T extends UserDto> HashMap<Long, T> listToHashMap(List<T> users) {
        HashMap<Long, T> res = new HashMap<>();
        for (T user : users) {
            res.put(user.getUserId(), user);
        }
        return res;
    }

    public static <T extends UserDto> Long getUserId(User user) {
        if (user == null) {
            throw new FreightException("登入失效或尚未登入，请先登入");
        }
        return user.getId();
    }

    /**
     * 判断表单中的userId 和当前登入人的关系
     *
     * @param user
     * @param userDto
     * @param <T>
     * @return
     */
    public static <T extends UserDto> Long getCurrentUserId(User user, T userDto) {
        return getCurrentUserId(user, userDto.userId);
    }

    /**
     * @param u
     * @return
     */
    public static boolean isAdminOrCompany(User u) {
        if (u == null) {
            return false;
        }
        if (!(u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN)
                || u.getUserType().equals(CommonConstant.USER_TYPE_COMPANY))) {
            return false;
        }
        return true;
    }


    /**
     * @param u
     * @return
     */
    public static boolean isAdminOrDriver(User u) {
        if (u == null) {
            return false;
        }
        if (!(u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN) || u.getUserType().equals(CommonConstant.USER_TYPE_DRIVER))) {
            return false;
        }
        return true;
    }

    /**
     * @param u
     * @return
     */
    public static boolean isAdmin(User u) {
        if (u == null) {
            return false;
        }
        if (!(u.getUserType().equals(CommonConstant.USER_TYPE_ADMIN))) {
            return false;
        }
        return true;
    }


    /**
     * 判断表单中的userId 和当前登入人的关系
     *
     * @param user
     * @param userId
     * @return
     */
    public static Long getCurrentUserId(User user, Long userId) {
        if (user == null) {
            throw new FreightException("登入失效或尚未登入，请先登入");
        }
        if (userId == null) {
            throw new FreightException("请传入用户Id");
        }
        if (user.getUserType().equals(CommonConstant.USER_TYPE_ADMIN)) {
            return userId;
        } else {
            if (user.getId().equals(userId)) {
                return userId;
            } else {
//                throw new FreightException("当前用户与上传用户id不符");
                return userId;
            }
        }

    }
}
